package com.situ.mall.admin.controller;

import com.situ.mall.admin.util.ImageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/")
public class ImageController {

    @GetMapping("/image")
    @ResponseBody
    public void image(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        ServletOutputStream sos = response.getOutputStream();
        String randomImag="";
        int i=0;
        while (i<4){
            int ran =(int)(Math.random()*52)+1;
            if(ran<=26){
                randomImag +=(char)(ran+64);
            }else {
                randomImag +=(char)(ran+70);
            }
            i++;
        }
        //流写出图像
        request.getSession().setAttribute("captcha",randomImag);

        ImageIO.write(ImageUtil.image(randomImag),"JPEG",sos);

        sos.flush();
        sos.close();
    }
}
